package com.easyui.service.impl;

import com.easyui.dao.MenuDAO;
import com.easyui.pojo.Menu;
import com.easyui.service.MenuService;
import com.easyui.shiro.MyShiroFilterFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuDAO menuDAO;

    @Override
    public List<Menu> getTreeMenu() {
        List<Menu> menuList = menuDAO.getMenuList();
        return makeTreeMenu(menuList);
    }

    public List<Menu> makeTreeMenu(List<Menu> menuList) {
        List<Menu> firstMenu = new ArrayList<>();
        Map<Integer, Menu> menuMap = new HashMap<>();
        for (Menu menu : menuList) {
            menuMap.put(menu.getId(), menu);
            if (menu.getParentId() == null) {
                firstMenu.add(menu);
            }
        }
        for (Menu menu : menuList) {
            if (menu.getParentId() != null && menuMap.containsKey(menu.getParentId())) {
                menuMap.get(menu.getParentId()).getChildren().add(menu);
            }
        }
        return firstMenu;
    }

    @Override
    public List<Menu> getUserMenu(Integer userId) {
        List<Menu> menuList = menuDAO.getUserMenu(userId);
        return makeTreeMenu(menuList);
    }

    @Autowired
    private MyShiroFilterFactoryBean myShiroFilterFactoryBean;

    @Override
    public void addMenu(Menu menu) {
        menuDAO.addMenu(menu);
        myShiroFilterFactoryBean.update();
    }

    @Override
    public void updateMenu(Menu menu) {
        menuDAO.updateMenu(menu);
        myShiroFilterFactoryBean.update();
    }

    @Override
    public void deleteMenu(Integer[] ids) {
        for (Integer id : ids) {
            menuDAO.deleteMenu(id);
        }
    }

    @Override
    public Menu getMenuById(Integer id) {
        return menuDAO.getMenuById(id);
    }

    @Override
    public void addUserMenu(Integer[] menuIds, Integer userId) {
        menuDAO.deleteUserMenu(userId);
        Map<String, Integer> params = new HashMap<>();
        params.put("userId", userId);
        for (Integer menuId : menuIds) {
            params.put("menuId", menuId);
            menuDAO.addUserMenu(params);
        }
    }

    @Override
    public List<Menu> getAllMenu() {
        return menuDAO.getMenuList();
    }

    @Override
    public List<Integer> getUserMenuIds(Integer userId) {
        return menuDAO.getUserMenuIds(userId);
    }
}
